<template>
    <div class="bg-gray-100 flex-1">
        <!-- 右侧内容区域 -->
        <div v-if="user.authenticationFlag !== '1'" class="flex p-4 items-center justify-center">
            <var-alert class="w-[40%]" type="warning" title="暂无权限访问" message="请先通过身份验证再访问该页面" />
        </div>
        <div v-if="user.authenticationFlag === '1'" class="flex-1 p-4">
            <!-- 标题和搜索框 -->
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-3xl font-semibold">
                    {{ user.departmentName }}
                    <var-button v-if="user.directorFlag === '0'" type="info" round icon-container color="#006263" @click="showCenterPopup = true">
                        <var-icon name="help-circle-outline" />
                    </var-button>
                    <var-button v-if="user.directorFlag === '1'" type="info" round icon-container color="#006263" @click="showCenterPopup = true">
                        <var-icon name="cog-outline" />
                    </var-button>
                </h2>
                <!-- 修改/获取 科室信息按钮弹窗-->
                <var-popup v-model:show="showCenterPopup">
                    <div class="p-9 h-[220px] w-[500px] bg-white rounded-lg shadow-lg">
                        <div class="flex items-center gap-2">
                            <div class="text-lg">我的科室：{{ user.departmentName }}</div>
                            <var-button v-if="user.directorFlag === '1'" text outline type="primary" text-color="#006263" @click="showEditDepartmentName = true">修改科室名称</var-button>
                        </div>
                        <div class="text-lg mt-4" v-if="user.directorFlag === '0'">我的职位：{{ user.identity }}</div>
                        <div class="text-lg mt-4" v-if="user.directorFlag === '1'">我的职位：科室负责人</div>
                        <div class="flex justify-center items-center gap-6 mt-8">
                            <var-button-group type="primary" mode="outline">
                                <var-button v-if="user.directorFlag === '1'" text-color="#006263" @click="showDisbandDepartmentDialog = true">解散科室</var-button>
                                <var-button v-if="user.directorFlag === '1'" text-color="#006263" @click="showTransferAuthority = true">权限转移</var-button>
                                <var-button text-color="#006263" @click="showExitDepartmentDialog = true">退出科室</var-button>
                            </var-button-group>
                        </div>
                        <div class="texl-2xl mt-4"></div>
                    </div>
                </var-popup>
            </div>
            <!-- 插入可视化组件 -->
            <div class="text-lg font-semibold justify mb-4">最近一周统计数据</div>
            <div class="mb-4 bg-white rounded-lg shadow-lg flex">
                <MyDepartmentEChart :chartData="chartData" :loading="chartLoading"  />
            </div>
            <!-- 我的科室表格 -->
            <div class="text-lg font-semibold justify mb-4">科室成员</div>
            <div class="bg-white p-2 rounded-lg shadow-md mx-auto">
                <div class="max-h-[528px] overflow-y-auto relative">
                    <table class="min-w-full">
                        <thead>
                            <tr>
                                <th class="sticky top-0 bg-gray-50 px-6 py-2 text-center text-base font-medium text-gray-500 z-10">职位</th>
                                <th class="sticky top-0 bg-gray-50 px-6 py-2 text-center text-base font-medium text-gray-500 z-10">姓名</th>
                                <th class="sticky top-0 bg-gray-50 px-6 py-2 text-center text-base font-medium text-gray-500 z-10">性别</th>
                                <th class="sticky top-0 bg-gray-50 px-6 py-2 text-center text-base font-medium text-gray-500 z-10">电话号码</th>
                                <th v-if="user.directorFlag == 1" class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-if="listLoading">
                                <td colspan="4" class="px-6 py-1.4 whitespace-nowrap text-center text-base text-gray-500">
                                    <var-loading description="LOADING" color="#006263" />
                                </td>
                            </tr>

                            <tr v-if="List.length === 0 && !listLoading">
                                <td colspan="4" class="px-6 py-1.4 whitespace-nowrap text-center text-base text-gray-500">暂无数据</td>
                            </tr>
                            <tr v-for="(record, index) in List" :key="index" class="odd:bg-white even:bg-gray-50" v-hover="{ color: 'var(--color-on-primary)', background: '#F0F0F0' }">
                                <td v-if="record.directorFlag == '0'" class="px-6 py-1 text-center text-base text-gray-500">{{ record.identity }}</td>
                                <td v-if="record.directorFlag == '1'" class="px-6 py-1 text-center text-base text-[#006263]">科室主任</td>
                                <td class="px-6 py-1 text-center text-base text-gray-900">{{ record.name }}</td>
                                <td class="px-6 py-1 text-center text-base text-gray-500">{{ record.sex }}</td>
                                <td class="px-6 py-1 text-center text-base text-gray-500">{{ record.phone }}</td>
                                <!-- 科室主任专属操作列 -->
                                <td v-if="user.directorFlag === '1'" class="px-6 py-1.5 text-center text-base text-gray-500">
                                    <var-button
                                        v-if="record.directorFlag === '0'"
                                        type="danger"
                                        color="#006263"
                                        @click="
                                            showDeleteMemberDialog = true;
                                            selectedMember = record;
                                        ">
                                        删除
                                    </var-button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <!-- 分页组件 -->
                <div class="flex justify-center mt-6">
                    <var-pagination :current="currentPage" :total="total" :size-option="[10, 20, 30]" :simple="true" @change="handlePageChange" style="color: #006263" />
                </div>
            </div>
        </div>
        <!-- 弹窗：修改科室名称 -->
        <var-dialog v-model:show="showEditDepartmentName" title="修改科室名称" confirm-button-text-color="red" persistent cancel-button-text-color="#006263" width="35vw" @before-close="handleBeforeClose">
            <var-loading description="LOADING" color="#006263" :loading="newDepartmentLoading">
                <div class="p-4">
                    <var-input v-model="newDepartment" variant="outlined" placeholder="请输入修改的科室名称（格式：xx医院xx科室）" focus-color="#006263" size="small" :rules="departmentRules" />
                </div>
            </var-loading>
        </var-dialog>

        <!-- 弹窗：转移权限 -->
        <var-dialog v-model:show="showTransferAuthority" title="转移权限" confirm-button-text-color="red" persistent cancel-button-text-color="#006263" width="35vw" @before-close="handleTransferAuthorityClose">
            <var-loading description="LOADING" color="#006263" :loading="transferLoading">
                <div class="p-4">
                    <var-select v-model="selectedDoctor" variant="outlined" placeholder="请选择成员" class="mb-4" focus-color="#006263">
                        <var-option v-for="option in departmentMembersOptions" :key="option.value" :label="option.label" :value="option.value" />
                    </var-select>
                </div>
            </var-loading>
        </var-dialog>
        <!-- 弹窗：退出科室 -->
        <var-dialog v-model:show="showExitDepartmentDialog" title="确认操作" persistent message="确定要退出科室吗？" confirm-button-text-color="red" cancel-button-text-color="#006263" @before-close="handleExitDepartmentClose">
            <var-loading description="LOADING" color="red" :loading="exitLoading">
                <div class="p-4">
                    <p class="text-lg text-red-500">确定要退出科室吗？请谨慎操作！</p>
                </div>
            </var-loading>
        </var-dialog>
        <!-- 弹窗：解散科室 -->
        <var-dialog v-model:show="showDisbandDepartmentDialog" title="确认操作" message="确定要解散科室吗？此操作不可逆！" confirm-button-text-color="red" cancel-button-text-color="#006263" @before-close="handleDisbandDepartmentClose">
            <var-loading description="LOADING" color="red" :loading="disbandLoading">
                <div class="p-4">
                    <p class="text-lg text-red-500">确定要解散科室吗？此操作不可逆！</p>
                </div>
            </var-loading>
        </var-dialog>
        <!-- 弹窗：删除成员确认 -->
        <var-dialog v-model:show="showDeleteMemberDialog" title="确认操作" confirm-button-text-color="red" cancel-button-text-color="#006263" @confirm="handleDeleteMember" @cancel="showDeleteMemberDialog = false">
            <var-loading description="LOADING" color="red" :loading="disbandLoading">
                <div class="p-4">
                    <p class="text-lg text-red-500">确定要删除成员 {{ selectedMember?.name }} 吗？</p>
                </div>
            </var-loading>
        </var-dialog>
    </div>
</template>

<script>
import MyDepartmentEChart from '../../components/MyDepartmentEChart.vue';
import dayjs from 'dayjs';
export default {
    name: 'userDepartment',
    components: {
        MyDepartmentEChart
    },
    data() {
        return {
            sexOptions: [
                { label: '男', value: 'MAN' },
                { label: '女', value: 'WOMAN' }
            ],
            departmentMembersOptions: [],
            List: [],
            currentPage: 1, // 当前页码
            pageSize: 10, // 每页显示的记录数
            total: 0, //总条数
            loading: false,
            listLoading: false,
            chartLoading: false,
            showEditDepartmentName: false, //控制修改科室名称弹窗显示
            showTransferAuthority: false, // 控制转移权限弹窗
            showExitDepartmentDialog: false, // 控制退出科室弹窗
            showDisbandDepartmentDialog: false, // 控制解散科室弹窗
            showDeleteMemberDialog: false, // 控制删除成员确认弹窗
            newDepartment: '', // 新科室名称
            newDepartmentLoading: false, // 修改科室名称的加载状态
            selectedMember: {}, // 当前选中的成员
            transferLoading: false, // 转移权限的加载状态
            exitLoading: false, // 退出科室的加载状态
            disbandLoading: false, // 解散科室的加载状态
            showCenterPopup: false,
            chartData: {}, // 用于存储后端返回的统计数据
            startDate: '', // 统计开始日期
            endDate: '' // 统计结束日期
        };
    },
    mounted() {
        if (this.user.authenticationFlag === '1') {
            this.getMyDepartment();
        }
        const today = dayjs(); // 使用 dayjs 获取当前日期
        this.endDate = today.subtract(1, 'day').format('YYYY-MM-DD'); // 格式化为 YYYY-MM-DDdayjs().subtract(1, 'day');
        this.startDate = today.subtract(7, 'day').format('YYYY-MM-DD');
        // 首次获取数据
        this.getDepartmentStatistics();
    },

    computed: {
        user() {
            return this.$store.user;
        }
    },
    methods: {
        //用户获取我的科室信息接口
        async getMyDepartment() {
            this.List = [];
            this.listLoading = true;
            const res = await this.$api.department.getMyDepartment({ pageNum: this.currentPage, pageSize: this.pageSize, type: 1 });
            this.listLoading = false;
            if (res.success) {
                this.List = res.data.list;
                this.total = res.data.total;
                this.departmentMembersOptions = this.List.filter((member) => member.userId !== this.user.userId).map((member) => ({
                    label: member.name,
                    value: member.userId
                }));
            } else {
                this.$api.notify.error('获取数据失败！');
            }
        },
        // 修改科室名称接口
        async handleBeforeClose(action, done) {
            if (action === 'confirm') {
                if (!this.newDepartment) {
                    this.$api.notify.error('请输入新的科室名称');
                    return;
                }
                this.newDepartmentLoading = true;
                const res = await this.$api.department.updateDepartment({
                    name: this.newDepartment,
                    departmentId: this.user.departmentId
                });
                this.newDepartmentLoading = false;
                if (res.success) {
                    this.$api.notify.success('修改科室名称成功');
                    this.showUpdate = false;
                    this.showEditDepartmentName = false;
                    await this.$store.user.updateMyInfo();
                } else {
                    this.$api.notify.error('修改科室名称失败！');
                }
            }
            done();
        },
        // 退出科室确认弹窗关闭前的逻辑
        async handleExitDepartmentClose(action, done) {
            if (action === 'confirm') {
                this.exitLoading = true;
                const res = await this.$api.department.exitDepartment();
                this.exitLoading = false;
                if (res.success) {
                    this.$api.notify.success('退出科室成功');
                    await this.$store.user.updateMyInfo();
                    this.showCenterPopup = false;
                } else {
                    this.$api.notify.error(res.error);
                }
            }
            done();
        },
        // 转移权限弹窗关闭前的逻辑
        async handleTransferAuthorityClose(action, done) {
            if (action === 'confirm') {
                this.transferLoading = true;
                const res = await this.$api.department.replaceDirector({
                    newDirectorId: this.selectedDoctor
                });
                this.transferLoading = false;
                if (res.success) {
                    this.showTransferAuthority = false;
                    this.showCenterPopup = false;
                    await this.$store.user.updateMyInfo();
                    await this.getMyDepartment();
                    this.$api.notify.success('权限转移成功');
                } else {
                    this.$api.notify.error(res.error || '权限转移失败');
                }
            }
            done();
        },
        // 解散科室弹窗关闭前的逻辑
        async handleDisbandDepartmentClose(action, done) {
            if (action === 'confirm') {
                this.disbandLoading = true;
                const res = await this.$api.department.delDepartment();
                this.disbandLoading = false;
                if (res.success) {
                    this.$api.notify.success('解散科室成功');
                    this.showCenterPopup = false;
                } else {
                    this.$api.notify.error('解散科室失败');
                }
            }
            done();
        },

        //科室主任删掉该科室成员
        async handleDeleteMember() {
            if (!this.selectedMember?.userId) {
                this.$api.notify.error('请选择成员');
                this.loading = false;
                return;
            }
            this.loading = true;
            const res = await this.$api.department.directorDelDepartmentMember({
                userId: this.selectedMember.userId
            });
            this.loading = false;
            if (res.success) {
                this.$api.notify.success('成员删除成功');
                this.showDeleteMemberDialog = false; // 确保弹窗关闭
                await this.getMyDepartment();
            } else {
                this.$api.notify.error(res.error || '删除成员失败');
            }
        },
        //可视化接口
        async getDepartmentStatistics() {
            this.chartLoading = true;
            const res = await this.$api.statistics.getDepartmentStatistics({
                startDate: this.startDate,
                endDate: this.endDate
            });
            this.chartLoading = false;
            if (res.success) {
                this.chartData = res.data.data;
            } else {
                this.$api.notify.error(res.error);
            }
        },
        // 处理分页变化
        handlePageChange(page, pageSize) {
            if (page !== this.currentPage) {
                this.currentPage = page;
                this.getMyDepartment();
            }
            if (this.pageSize !== pageSize) {
                this.pageSize = pageSize;
                this.currentPage = 1; // 切换分页大小时重置到第一页
                this.getMyDepartment();
            }
        }
    }
};
</script>
<style scoped></style>
